#!/bin/tcsh -ef
####
#
#############################################################################
#                                                                           #
# Title: Final Merge                                                        #
#                                                                           #
# (C) 2dx.org, GNU Plublic License.                                         #
#                                                                           #
# Created..........: 01/03/2007                                             #
# Last Modification: 01/03/2007                                             #
# Author...........: 2dx.org                                                #
#                                                                           #
#############################################################################
#
# SORTORDER: 80
#
# MANUAL: This script allows merging the selected image data into one merge dataset.
#
# MANUAL: Now merge all images together into a merged final dataset.
#
# PUBLICATION: 3D reconstruction of two-dimensional crystals: <A HREF="http://www.ncbi.nlm.nih.gov/pubmed/26093179">Arch Biochem Biophys 581, 68-77 (2015)</A>
# PUBLICATION: 3D Reconstruction from 2D crystal image and diffraction data: <A HREF="http://dx.doi.org/10.1016/S0076-6879(10)82004-X">Methods Enzymol. 482, Chapter 4, 101-129 (2010)</A>
# PUBLICATION: 2dx - Automated 3D structure reconstruction from 2D crystal data: <A HREF="http://journals.cambridge.org/action/displayAbstract?aid=1943200">Microscopy and Microanalysis 14(Suppl. 2), 1290-1291 (2008)</A>
# PUBLICATION: 2dx_merge - Data management and merging for 2D crystal images: <A HREF="http://dx.doi.org/10.1016/j.jsb.2007.09.011">J. Struct. Biol. 160(3), 375-384 (2007)</A>
#
# DISPLAY: MergeResolution
# DISPLAY: zstarrange
# DISPLAY: zstarrange_real
# DISPLAY: RESMIN
# DISPLAY: RESMAX
# DISPLAY: merge_res_limit
# DISPLAY: tempkeep
# DISPLAY: realcell
# DISPLAY: realang
# DISPLAY: ALAT
# DISPLAY: SYM
# DISPLAY: avrgamphsNUMBER
# DISPLAY: avrgamphsRESOL
# DISPLAY: ILIST
# DISPLAY: MergeIQMAX
# DISPLAY: Merge_Reference_IQMAX
# DISPLAY: MergeHKMAX
# DISPLAY: Merge_Reference_HKMAX
# DISPLAY: MergeRminRmax
# DISPLAY: MergeAK
# DISPLAY: MergeLatLine_MaxAmpFactor
# DISPLAY: MergeLatLine_REDUCAC
# DISPLAY: MergeLatLine_RFOMSCALE
# DISPLAY: max_amp_correction
# DISPLAY: merge_data_type
# DISPLAY: plotres_rings
# DISPLAY: scalimamp3d_rref
# DISPLAY: scalimamp3d_BXYMINMAX
# DISPLAY: scalimamp3d_BZMINMAX
# DISPLAY: AMP_Scale_Factor
# DISPLAY: scalimamp3d_BEXTRA
# DISPLAY: resolutionplot_RESMAX
# DISPLAY: resolutionplot_bins
# DISPLAY: RFACAMP
# DISPLAY: Thread_Number
# DISPLAY: merge_alsoevenodd
#
#$end_local_vars
#
set bin_2dx = ""
set proc_2dx = ""
#
set ALAT = ""
set AMP_Scale_Factor = ""
set avrgamphsNUMBER = ""
set avrgamphsRESOL = ""
set ILIST = ""
set lattice = ""
set max_amp_correction = ""
set merge_data_type = ""
set merge_ref_num = ""
set Merge_Reference_HKMAX = ""
set Merge_Reference_IQMAX = ""
set merge_res_limit = ""
set MergeAK = ""
set MergeHKMAX = ""
set MergeIQMAX = ""
set MergeResolution = ""
set MergeRminRmax = ""
set num_amplitudes_observed = ""
set num_phases_observed = ""
set num_reflections_fitted = ""
set num_reflections_FOM50 = ""
set overall_phase_residual = ""
set overall_R_factor = ""
set overall_weighted_phase_residual = ""
set overall_weighted_R_factor = ""
set plotres_rings = ""
set realang = ""
set realcell = ""
set Reflections_Unique = ""
set RESMAX = ""
set RESMIN = ""
set resolutionplot_bins = ""
set resolutionplot_RESMAX = ""
set RFACAMP = ""
set scalimamp3d_BEXTRA = ""
set scalimamp3d_BXYMINMAX = ""
set scalimamp3d_BZMINMAX = ""
set scalimamp3d_rref = ""
set SYM = ""
set tempkeep = ""
set Thread_Number = ""
set zstarrange  = ""
set zstarrange_real = ""
set zstarwin  = ""
set ctfrev = ""
set merge_alsoevenodd = ""
#
#$end_vars
#
set scriptname = 2dx_finalmerge
set merge_modus="3D"
#
\rm -f LOGS/${scriptname}.results
#
set ccp4_setup = 'y'
source ${proc_2dx}/initialize
#
# The following is to make sure that for the next "Import Images", the default is correctly initialized.
set initialization_reset = "y"
set initialization_executable = "y"
echo "set initialization_reset = ${initialization_reset}" >> LOGS/${scriptname}.results
echo "set initialization_executable = ${initialization_executable}" >> LOGS/${scriptname}.results
#
set zstarrange = `echo ${zstarrange_real} ${ALAT} | awk '{ s = 1.0 / ( $1 ) } END { print s }'`
echo "set zstarrange = ${zstarrange}" >> LOGS/${scriptname}.results
${proc_2dx}/linblock "Calculating zstarrange as ${zstarrange} (with 0.5 = Nyquist resolution)."
#
set zmin = `echo ${zstarrange} | awk '{s = -$1} END {print s}'`
set zminmax = `echo ${zmin},${zstarrange}`
echo zminmax = ${zminmax}
#
echo "<<@progress: 1>>"
#
#################################################################################
${proc_2dx}/linblock "Verifying some parameters"
#################################################################################
#
if ( ${merge_alsoevenodd} == "y" && ( ! -e 2dx_merge_dirfile_even.dat || ! -e 2dx_merge_dirfile_odd.dat )) then
  echo ":: "
  echo ":: "
  ${proc_2dx}/linblock "ERROR: First define EVEN and ODD image tags, using the Project Tool"
  ${proc_2dx}/protest "This is the button top left in the GUI"
endif
#
if ( `echo ${RESMIN} ${RESMAX} | awk '{ if ( $1 < $2 ) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
  set oldval = ${RESMIN}
  set RESMIN = ${RESMAX}
  set RESMAX = ${oldval}
  ${proc_2dx}/linblock "ERROR: exchanging RESMIN and RESMAX, to RESMIN=${RESMIN}, and RESMAX=${RESMAX}"
  echo "set RESMIN = ${RESMIN}" >> LOGS/${scriptname}.results
  echo "set RESMAX = ${RESMAX}" >> LOGS/${scriptname}.results
endif
#
if ( ${AMP_Scale_Factor}x == 'x' ) then
  set AMP_Scale_Factor = 0.001
  echo "set AMP_Scale_Factor = ${AMP_Scale_Factor}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "WARNING: AMP_Scale_Factor corrected to ${AMP_Scale_Factor}"
endif
# 
if ( ${ILIST}x == 'x' ) then
  set ILIST = "n"
  echo "set ILIST = ${ILIST}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "WARNING: ILIST corrected to ${ILIST}"
endif
#
if ( ${ILIST} == "n" ) then
  set ILIST_VAL = 0
else
  set ILIST_VAL = 1
endif
#
# This translates the list of directories to work on into one single long line:
cat 2dx_merge_dirfile.dat | tr "\n" " " > SCRATCH/2dx_merge_dirfile_oneline.dat
set dirlist = "`cat SCRATCH/2dx_merge_dirfile_oneline.dat`"
#
# This memorizes the current merge directory under the variable "olddir":
set olddir = $PWD
#
echo "The current working directory is" ${olddir}
#
echo "<<@progress: 5>>"
echo "<<@evaluate>>"
#
#############################################################################
${proc_2dx}/linblock "sourcing sym2spsgrp_sub.com"
#############################################################################
#
source ${proc_2dx}/2dx_sym2spcgrp_sub.com
#
echo SYM = ${SYM}
echo spcgrp = ${spcgrp}
echo CCP4_SYM = ${CCP4_SYM}
#
############################################################################# 
${proc_2dx}/lin "2dx_merge_makedirs - to create all required subdirectories"
#############################################################################
#
source ${proc_2dx}/2dx_merge_makedirs
#
echo "<<@progress: 10>"
#
if ( ${merge_alsoevenodd} == "y" ) then
  echo ":: "
  #############################################################################
  ${proc_2dx}/linblock "Switching to EVEN IMAGES series"
  #############################################################################
  set dirfile = "2dx_merge_dirfile_even.dat"
  set select_mode = "even"
  #
  ${proc_2dx}/linblock "Sourcing 2dx_origtilt_merge.com"
  source ${proc_2dx}/2dx_origtilt_merge.com
  \cp -f APH/merge.aph APH/merge_even.aph
  echo "# IMAGE: APH/merge_even.aph <HKL: Generated merge_even.aph>" >> LOGS/${scriptname}.results
  echo "<<@progress: +5>>"
  #############################################################################
  ${proc_2dx}/linblock "Sourcing 2dx_merge_generate3D.com"
  source ${proc_2dx}/2dx_merge_generate3D.com
  echo "<<@progress: +5>>"
  #
  cp APH/merge.aph APH/merge_even.aph
  cp APH/latfitted.hkl APH/latfitted_even.hkl
  cp merge3Dref_MRClefthanded.mtz merge3Dref_MRClefthanded_even.mtz
  echo "# IMAGE: APH/latfitted_even.hkl <HKL: Generated HKL EVEN [H,K,L,A,PHI,FOM]>" >> LOGS/${scriptname}.results
  #
  echo "<<@evaluate>>"
  echo ":: "
  #############################################################################
  ${proc_2dx}/linblock "Switching to ODD IMAGES series"
  #############################################################################
  set dirfile = "2dx_merge_dirfile_odd.dat"
  set select_mode = "odd"
  #
  ${proc_2dx}/linblock "Sourcing 2dx_origtilt_merge.com"
  source ${proc_2dx}/2dx_origtilt_merge.com
  \cp -f APH/merge.aph APH/merge_odd.aph
  echo "# IMAGE: APH/merge_odd.aph <HKL: Generated merge_odd.aph>" >> LOGS/${scriptname}.results
  echo "<<@progress: +5>>"
  #############################################################################
  ${proc_2dx}/linblock "Sourcing 2dx_merge_generate3D.com"
  source ${proc_2dx}/2dx_merge_generate3D.com
  echo "<<@progress: +5>>"
  echo "<<@evaluate>>"
  #
  cp APH/merge.aph APH/merge_odd.aph
  cp APH/latfitted.hkl APH/latfitted_odd.hkl
  cp merge3Dref_MRClefthanded.mtz merge3Dref_MRClefthanded_odd.mtz
  echo "# IMAGE: APH/latfitted_odd.hkl <HKL: Generated HKL ODD [H,K,L,A,PHI,FOM]>" >> LOGS/${scriptname}.results
  #
  echo ":: "
  #############################################################################
  ${proc_2dx}/linblock "Switching to ALL IMAGES series"
  #############################################################################
endif
#
echo "<<@evaluate>>"
set dirfile = "2dx_merge_dirfile.dat"
set select_mode = "all"
#
${proc_2dx}/linblock "Sourcing 2dx_origtilt_merge.com"
source ${proc_2dx}/2dx_origtilt_merge.com
\cp -f APH/merge.aph APH/merge_all.aph
echo "# IMAGE: APH/merge_all.aph <HKL: Generated merge_all.aph>" >> LOGS/${scriptname}.results
echo "<<@progress: +5>>"
#############################################################################
${proc_2dx}/linblock "Sourcing 2dx_plttilt.com"
source ${proc_2dx}/2dx_plttilt.com
echo "<<@progress: +5>>"
#############################################################################
${proc_2dx}/linblock "Sourcing 2dx_merge_generate3D.com"
source ${proc_2dx}/2dx_merge_generate3D.com
echo "# IMAGE: APH/latfitted.hkl <HKL: Generated HKL [H,K,L,A,PHI,FOM]>" >> LOGS/${scriptname}.results
echo "<<@progress: +5>>"
#
#############################################################################
${proc_2dx}/linblock "${scriptname} normal end."
#############################################################################
#
echo "<<@progress: 100>>"
#
exit
# for GUI:
source ${proc_2dx}/2dx_hkl_to_mtz.com
#
